﻿Imports System.Net
Imports System.IO

Public Class frmYoutube
    Public request As HttpWebRequest
    Public request2 As HttpWebRequest
    Public response As HttpWebResponse
    Public source As String

    Public response2 As HttpWebResponse
    Public source2 As String
    Public WithEvents web As New WebClient
    Public downloadurl As String
    Delegate Sub OneArgD(ByVal arg As Object)

    Private Sub btnButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnButton1.Click
        request = DirectCast(HttpWebRequest.Create(txtTextBox1.Text), HttpWebRequest)
        response = DirectCast(request.GetResponse, HttpWebResponse)
        source = New StreamReader(response.GetResponseStream, System.Text.Encoding.Default).ReadToEnd
        If source.IndexOf("video_id") > -1 Then
            'This grabs the .flv location URL ready for doownloading.
            Dim signature As String = source
            signature = System.Text.RegularExpressions.Regex.Split(signature, (ChrW(34) + "fmt_url_map" + ChrW(34) + ": " + ChrW(34)))(1)
            'This changes the URL to conform to internet standards eg. %20 = " "
            signature = signature.Remove(0, 5)
            signature = signature.Replace("%252C", ",")
            signature = signature.Replace("%2F", "/")
            signature = signature.Replace("%3D", "=")
            signature = signature.Replace("%3F", "?")
            signature = signature.Replace("%3A", ":")
            signature = signature.Replace("%26", "&")
            Dim sig2 As String = signature
            sig2 = sig2.IndexOf("http", 30)
            signature = signature.Remove(sig2, signature.Length - sig2)
            signature = signature.Remove(signature.IndexOf("%"), 7)
            'Removes any remaining % characters from the string.
            signature = signature.Replace("%", "")
            'Checks for and Removes any remaining C characters from the string.
            If signature.Chars(signature.Length - 1) = "C" Then
                signature = signature.Remove(signature.Length - 1, 1)
            End If
            backgroundWorker1.RunWorkerAsync()
            downloadurl = "ht" & signature.ToString()
            request2 = DirectCast(HttpWebRequest.Create("ht" & signature), HttpWebRequest)
            response2 = DirectCast(request2.GetResponse, HttpWebResponse)
            If response2.ContentType = "video/x-flv" Then
                SaveFileDialog1.Filter = "FLV Files (.flv) |*.flv"
            ElseIf response2.ContentType = "video/mp4" Then
                SaveFileDialog1.Filter = "MP4 Files (.mp4) |*.mp4"
            Else
                MsgBox("An Error occured and the requested file(s) could not be downloaded." + vbCrLf + "This is normally caused by changes to the You-Tube Website.", MsgBoxStyle.Critical)
                Exit Sub
            End If
            If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                backgroundWorker1.RunWorkerAsync()
            Else
                MsgBox("Download Canceled!")
            End If
        Else
            MsgBox("Error! Please check the Video URL!")
        End If
    End Sub

    Private Sub txtTextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTextBox1.TextChanged
        If txtTextBox1.Text = "" Then
            btnButton1.Enabled = False
        Else
            btnButton1.Enabled = True
        End If
    End Sub

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        web.DownloadFileAsync(New Uri(downloadurl.ToString), SaveFileDialog1.FileName)
    End Sub



    Public Sub DownloadingFile(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs) Handles web.DownloadProgressChanged
        Dim deleg As New OneArgD(AddressOf SetValue)
        prgProgressBar1.Invoke(deleg, e.ProgressPercentage)
        If e.ProgressPercentage = 100 Then
            MsgBox("Download has finished.", MsgBoxStyle.Information)
        End If
    End Sub

    Private Sub SetValue(ByVal max As Object)
        Me.prgProgressBar1.Value = CInt(max)
    End Sub

End Class